import json
import logging

from fastapi import APIRouter, Depends
from fastapi.responses import StreamingResponse
from services.chat_service import ChatService  # 导入优化后的ChatService
from models.chat_schemas import ChatRequest, ChatHistoryResponse, ChatHistoryResponseOther
from models.JsonData import JsonData
from agents.small_chat_agent import generate_stream_response  # 导入适配后的智能体函数
from core.auto import get_current_user
from core.exception import ApiException
from typing import Dict, Any, AsyncGenerator
from services.small_chat_service import replace_response_content
import logging

logger = logging.getLogger(__name__)

# 初始化路由（保持原prefix和tags不变）
router = APIRouter(
    prefix="/api/small_chat",
    tags=["AI聊天助手"],
)



# 异步依赖函数
async def get_chat_service() -> ChatService:
    """
    异步依赖注入函数：在异步上下文内创建ChatService实例
    确保实例与路由运行在同一个事件循环，避免Redis连接的事件循环不一致问题
    """
    chat_service = ChatService()
    return chat_service



# 流式聊天接口
@router.post("/stream")
async def chat_stream(
        request: ChatRequest,
        chat_service: ChatService = Depends(get_chat_service),
        current_user: Dict[str, Any] = Depends(get_current_user)
):
    # 获取当前用户账号
    account_no = current_user.get("accountNo")
    if not account_no:
        raise ApiException(msg="用户账号获取失败，请重新登录")


    print(f"用户{account_no}开始聊天，消息：{request.message[:50]}...")

    # 调用智能体生成原始流式响应
    original_response = generate_stream_response(
        chat_service=chat_service,
        message=request.message,
        account_no=account_no
    )

    # 处理响应内容
    modified_response = replace_response_content(original_response)

    # 构造StreamingResponse返回前端
    return StreamingResponse(
        content=modified_response,
        media_type="text/event-stream",
        headers={
            "Cache-Control": "no-cache",
            "Connection": "keep-alive",
            "X-Accel-Buffering": "no"
        }
    )



# 获取聊天历史接口（适配异步ChatService）
@router.get("/history")
async def get_chat_history(
        chat_service: ChatService = Depends(get_chat_service),
        current_user: Dict[str, Any] = Depends(get_current_user)
):
    """获取当前用户的聊天历史记录（适配前端格式）"""
    account_no = current_user.get("accountNo")
    if not account_no:
        raise ApiException(msg="用户账号获取失败，请重新登录")


    raw_history = await chat_service.get_chat_history(account_no=account_no)
    if not raw_history:

        return ChatHistoryResponseOther(
            code=0,
            msg="暂无聊天历史",
            data=[],
            total=0
        )


    formatted_history = [
        {
            "content": item["content"],
            "isAI": item["role"].lower() == "assistant",
            "timestamp": item["timestamp"]
        }
        for item in raw_history
    ]

    # 按时间戳排序
    history_sorted = sorted(
        formatted_history,
        key=lambda x: x["timestamp"],
        reverse=False
    )

    # 返回适配后的响应
    return ChatHistoryResponseOther(
        code=0,
        msg="获取成功",
        data=history_sorted,
        total=len(history_sorted)
    )



# 新增：清空聊天记录接口
@router.delete("/clear")
async def clear_chat(
        chat_service: ChatService = Depends(get_chat_service),
        current_user: Dict[str, Any] = Depends(get_current_user)
):
    """清空当前用户的所有聊天记录（包括历史消息、摘要和索引）"""
    account_no = current_user.get("accountNo")
    if not account_no:
        raise ApiException(msg="用户账号获取失败，请重新登录")

    try:
        # 调用ChatService的清空方法
        await chat_service.clear_chat_history(account_no)
        return {
            "code": 0,
            "msg": "聊天记录已成功清空",
            "data": None
        }
    except Exception as e:
        logger.error(f"清空聊天记录失败（用户：{account_no}）：{str(e)}", exc_info=True)
        raise ApiException(msg="清空聊天记录失败，请稍后重试")